import React from 'react';
import styles from './ExternalLayout.less';
import PropTypes from 'prop-types';
import Permissions from '../pages/external/permissions';
import { connect } from 'dva';

class ExternalLayout extends React.Component<any, any> {
  static childContextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };
  getChildContext() {
    const permissions = Permissions.map(e => `/external${e}`);
    this.props.dispatch({ type: 'menu/save', payload: { permissions } });
    return {
      permissions,
      dicData: [],
    };
  }

  state = {
    // 1 权限加载中
    // 2 鉴权通过
    // 3 鉴权不通过
    isLogin: 1,
  };

  componentDidMount() {
    if (this.props.location.pathname.startsWith('/external/electricFence/')) {
      // 电子围栏外链特殊 token 获取
      const { sign, secretCode, orgCode } = this.props.location.query;
      fetch(
        `${window['g'].url}/account/getopentoken?sign=${sign}&secretCode=${secretCode}&orgCode=${orgCode}`,
      )
        .then(e => e.json())
        .then(e => {
          sessionStorage.setItem('token', e.data);
          this.setState({ isLogin: 2 });
        })
        .catch(e => {
          this.setState({ isLogin: 3 });
        });
    } else {
      this.setState({ isLogin: 2 });
    }
  }

  render() {
    if (this.state.isLogin === 1) {
      return <div style={{ margin: '30px', fontSize: '20px' }}>加载中</div>;
    } else if (this.state.isLogin !== 2) {
      return <div style={{ margin: '30px', fontSize: '20px' }}>鉴权失败</div>;
    }
    const { children } = this.props;
    return <div className={styles.content}>{children}</div>;
  }
}

export default connect()(ExternalLayout);
